import {Component} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {UserEditComponent} from "../edit/user-edit.component";
import {UserRoleComponent} from "../role/user-role.component";
import {GnDigestUtils, GnMessageService, GnTable} from "geminis-ng";
import {GnTableColumn} from "geminis-ng/data/table.component";

@Component({
  selector: 'gn-resources-user-list',
  templateUrl: './user-list.component.html'
})
export class UserListComponent extends GnTable {

  typeEdit = UserEditComponent;
  typeRole = UserRoleComponent;

  columns: GnTableColumn[] = [
    {label: '登录名', field: 'user.id', formatter: row => row.user.id},
    {label: '名称', field: 'user.name', formatter: row => row.user.name},
    {label: '关系', field: 'type'},
    {label: '角色', field: 'user.role', formatter: row => row.user.roles.map(role => role.name).join(",")}
  ];

  constructor(private httpClient: HttpClient,
              private messageService: GnMessageService) {
    super();
  }

  getRoleName(roles: Array<any>): string {
    return roles.map(role => role.name).join(",");
  }

  refreshTable(selectedId: string): void {
    this.table.filterGroup = {
      type: 'and',
      childGroups: [],
      filters: [
        {
          field: 'organization.id',
          compareType: selectedId === null ? 'is null' : '=',
          value: selectedId === null ? 'null' : selectedId
        }
      ]
    }
    this.table.cleanSelectionAndLoadData();
  }

  delete(): void {
    this.table.deleteData("/RESOURCES-SERVICE/users", this.table.selection.selected.map(data => data.user.id));
  }

  resetPassword(): void {
    this.messageService.confirm('重置用户密码?').subscribe(() => {
      this.table.selection.selected.forEach(orgUser => {
        GnDigestUtils.sha256(orgUser.user.id)
          .then(value => {
            this.httpClient.put('/RESOURCES-SERVICE/users/' + orgUser.user.id + '/resetPassword?password=' + value, null)
              .subscribe(() => {
                this.messageService.success('密码已重置');
              }, error => {
                this.messageService.error({message: '密码重置错误', error: error});
              });
          });
      });
    });
  }
}

